import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/data/entity.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/reg_exp_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/verify_code_exception_help.widget.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../common/utils/log_utils.dart';

/// @Author lixiaobin
/// @Date 2023/12/5
/// @Description 更换手机号
class BindPhoneNumPage extends StatefulWidget {
  const BindPhoneNumPage({super.key});

  @override
  State<BindPhoneNumPage> createState() => _ModifyPhoneNumPageState();
}

class _ModifyPhoneNumPageState extends State<BindPhoneNumPage> {
  final _smsTextEditingController = TextEditingController();
  final _phoneTextEditingController = TextEditingController();
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  int _countValue = 0;
  Timer? _timer;
  bool _isBindSuccess = false;

  @override
  void initState() {
    super.initState();
    _smsTextEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    var btnIsSelect = _smsTextEditingController.text.isNotEmpty &&
        _phoneTextEditingController.text.isNotEmpty;
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context,
          title: _isBindSuccess ? '更换成功' : null),
      body: _isBindSuccess
          ? _buildBindSucceedLayout()
          : _buildBindLayout(btnIsSelect),
    );
  }

  ///绑定新手机号码页面
  Widget _buildBindLayout(bool btnIsSelect) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          height: 56.w,
          padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w),
          width: double.infinity,
          child: TextField(
            controller: _phoneTextEditingController,
            inputFormatters: [
              LengthLimitingTextInputFormatter(11),
              FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
            ],
            decoration: const InputDecoration(
                hintText: '请输入手机号', border: InputBorder.none),
          ),
        ),
        CommWidget.buildLine(),
        Container(
          height: 56.w,
          padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 8.w),
          width: double.infinity,
          child: Row(
            children: [
              Expanded(
                  child: TextField(
                controller: _smsTextEditingController,
                inputFormatters: [
                  LengthLimitingTextInputFormatter(6),
                  FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                ],
                decoration: const InputDecoration(
                    hintText: '请输入验证码', border: InputBorder.none),
              )),
              GestureDetector(
                onTap: () => _getSms(),
                child: Container(
                    height: 30.w,
                    padding: EdgeInsets.only(left: 10.w, right: 10.w),
                    alignment: Alignment.center,
                    child: Text(
                        _countValue == 0 ? '获取验证码' : '重新获取（${_countValue}s）',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: _countValue == 0
                                ? ColorRes.colorMain
                                : ColorRes.color9A9A9A,
                            fontSize: 15.sp))),
              )
            ],
          ),
        ),
        CommWidget.buildLine(),
        SizedBox(
          height: 10.w,
        ),
        VerifyCodeExceptionHelpWidget(),
        SizedBox(
          height: 52.w,
        ),
        Padding(
            padding: EdgeInsets.only(left: 16.w, right: 16.w),
            child: CommWidget.buildRightBtn('确定', () => _submit(),
                isSelect: btnIsSelect)),
      ],
    );
  }

  Widget _buildBindSucceedLayout() {
    var phone = _phoneTextEditingController.text;
    var privateNumber = StringUtils.showNewNumber(phone);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(height: 100.w),
        ImageLoader.loadAsset('icon_bind_succeed_bg.webp', 204.w),
        SizedBox(height: 22.w),
        Text('更换新手机号成功',
            style: TextStyle(color: ColorRes.color333333, fontSize: 18.sp)),
        SizedBox(height: 4.w),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('当前登录账号：',
                style: TextStyle(color: ColorRes.color333333, fontSize: 15.sp)),
            Text(privateNumber ?? '',
                style: TextStyle(color: ColorRes.colorMain, fontSize: 15.sp))
          ],
        ),
        SizedBox(height: 40.w),
        SizedBox(
            width: 260.w, child: CommWidget.buildRightBtn('重新登录', () => _reLogin())),
      ],
    );
  }

  @override
  void dispose() {
    // 组件销毁时判断Timer是否仍然处于激活状态，是则取消
    if (_timer?.isActive == true) {
      _timer?.cancel();
    }
    super.dispose();
  }

  /// 启动Timer
  _startTimer() {
    const Duration duration = Duration(seconds: 1);
    cancelTimer();

    _timer = Timer.periodic(duration, (timer) {
      _countValue -= 1;
      Log.d(_countValue);
      if (_countValue <= 0) {
        cancelTimer();
      }
      setState(() {});
    });
  }

  /// 结束timer
  void cancelTimer() {
    if (_timer != null) {
      _timer?.cancel();
    }
  }

  /// 获取验证码
  _getSms() async {
    if (_countValue > 0) return;
    var phone = _phoneTextEditingController.text;
    if (phone.length != 11) {
      ToastUtils.showToast(context, '请输入11位手机号');
      return;
    }
    if (!RegExpUtils.isPhoneNumber(phone)) {
      ToastUtils.showToast(context, '请输入合法手机号码');
      return;
    }
    _countValue = 60;
    var httpRequest = HttpRequest(Api.sendSms, body: {
      'phone': phone,
      "purpose": 'updateLoginNameVerifyCode',
    });
    var httpResponse = await HttpClient.post(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      _startTimer();
    } else {
      ToastUtils.showToast(context, serviceResult.responseMsg);
    }
  }

  /// 绑定新手机号
  _submit() async {
    var smsCode = _smsTextEditingController.text;
    var phone = _phoneTextEditingController.text;
    var uId = App.instance.userInfo?.id;
    if (phone.length != 11) {
      ToastUtils.showToast(context, '请输入11位手机号');
      return;
    }
    if (!RegExpUtils.isPhoneNumber(phone)) {
      ToastUtils.showToast(context, '请输入合法手机号码');
      return;
    }
    if (smsCode.length < 6) {
      ToastUtils.showToast(context, "请输入正确的验证码");
      return;
    }
    _countValue = 60;
    var httpRequest = HttpRequest(Api.updateMedicalLoginName, body: {
      "loginName": phone,
      "medicalId": uId,
      'code': smsCode,
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var serviceResult = ServiceResult<String?>.simple(httpResponse);
    if (serviceResult.success) {
      _isBindSuccess = true;
      var sharedPreferences = await _prefs;
      sharedPreferences.setBool(Entity.changePhone, true);
      setState(() {});
    } else {
      ToastUtils.showToast(context, serviceResult.responseMsg);
    }
  }

  /// 重新登录
  _reLogin() async {
    await NativeInterface().confirmLogOut();
  }
}
